from .serializers import *
from .FilterBackends import *

from . import tasks as TASKS
from iClouds.apidev import RC4, has_PassWordB
from PlaceManager.tasks import has_pid_from_idcode
from mysqldb.weChatSDK import requests_Wechat_SDK
from mysqldb.tasks import WeAppsOpenidformSend
from mysqldb.redis import redis_key_get
import base64
import json
import logging

logger = logging.getLogger(__name__)
# Create your views here.


class NewGamePlacetokenListViewSet(viewsets.ModelViewSet):
    __title__ = "创建认证账户"
    __group__ = "游戏活动"
    __info__ = {"post": "创建认证账户"}
    __doc__ = """
    create:
    <h4>创建认证账户</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [] if settings.DEBUG else [MyJWTAuthentication]
    permission_classes = [AllPermissions] if settings.DEBUG else [MyPermissions]
    serializer_class = NewGamePlacetokenListSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()

        with transaction.atomic():
            r = GamePlacetokenList(
                id=serializer.data["pid"],
                status=1,
                appid=has_PassWordB(8, 1),
                secret=has_PassWordB(16, 2),
                created=timezone.now(),
                outdate=timezone.now().date() + timedelta(days=3),
            )
            r.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class LoadGameConfListViewSet(viewsets.ModelViewSet):
    __title__ = "登录服务器"
    __group__ = "游戏活动"
    __info__ = {"post": "登录服务器"}
    __doc__ = """
    create:
    <h4>登录服务器</h4>
        header: "TOKEN":"{token}"
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = LoadGameConfListSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        try:
            r = GamePlacetokenList.objects.get(
                appid=serializer.data["appid"],
                secret=serializer.data["secret"],
                status=1,
                outdate__gt=timezone.now(),
            )

            p = AllinpayPlaceList.objects.get(id=r.id)
        except BaseException as err:
            raise serializers.ValidationError(f"登录失败 {err}")
        else:
            x = f"{r.id}-{r.appid}-{r.secret}-{r.outdate}-{timezone.now()}"
            encrypt_func, decrypt_func = RC4()
            encrypted_data = encrypt_func(x.encode("utf-8"))
            r.lasted = base64.b64encode(encrypted_data).decode(encoding="utf-8")
            r.save()
        return Response(
            {
                "rescode": 200,
                "resmsg": {
                    "place": p.id,
                    "name": p.basename,
                    "wb_id": p.barcode,
                    "token": {"AUTHORIZATION": f"Xearer {r.lasted}"},
                },
            }
        )


# ================================================================================


class GamePlaceconfLolBaseViewSet(viewsets.ModelViewSet):
    __title__ = "LOL配置基本"
    __group__ = "游戏活动"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "创建LOL配置基本",
        "put": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>创建LOL配置基本</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GamePlaceconfLolBaseSerializer
    queryset = GamePlaceconfLolBase.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class GamePlaceconfLolLevelViewSet(viewsets.ModelViewSet):
    __title__ = "LOL段位系数"
    __group__ = "游戏活动"
    __info__ = {
        "get": "查询LOL段位系数列表",
        "post": "创建LOL段位系数",
        "put": "编辑LOL段位系数",
        "delete": "移除LOL段位系数",
    }
    __doc__ = """	list:
    <h4>LOL段位系数列表</h4>
    retrieve:
    <h4>LOL段位系数详情</h4>
    create:
    <h4>创建LOL段位系数</h4>
    update:
    <h4>编辑LOL段位系数</h4>
    delete:
    <h4>移除LOL段位系数</h4>"""
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GamePlaceconfLolLevelSerializer
    queryset = GamePlaceconfLolLevel.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class GamePlaceconfLolTypesViewSet(viewsets.ModelViewSet):
    __title__ = "LOL赛制系数"
    __group__ = "游戏活动"
    __info__ = {
        "get": "查询LOL赛制系数",
        "post": "创建LOL赛制系数",
        "put": "编辑LOL赛制系数",
        "delete": "移除LOL赛制系数",
    }
    __doc__ = """	list:
    <h4>LOL赛制系数列表</h4>
    retrieve:
    <h4>LOL赛制系数详情</h4>
    create:
    <h4>创建LOL赛制系数</h4>
    update:
    <h4>编辑LOL赛制系数</h4>
    delete:
    <h4>移除LOL赛制系数</h4>"""
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GamePlaceconfLolTypesSerializer
    queryset = GamePlaceconfLolTypes.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class GamePlaceconfLolGroupViewSet(viewsets.ModelViewSet):
    __title__ = "LOL大区系数"
    __group__ = "游戏活动"
    __info__ = {
        "get": "查询LOL大区系数",
        "post": "创建LOL大区系数",
        "put": "编辑LOL大区系数",
        "delete": "移除LOL大区系数",
    }
    __doc__ = """	list:
    <h4>LOL大区系数列表</h4>
    retrieve:
    <h4>LOL大区系数详情</h4>
    create:
    <h4>创建LOL大区系数</h4>
    update:
    <h4>编辑LOL大区系数</h4>
    delete:
    <h4>移除LOL大区系数</h4>"""
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GamePlaceconfLolGroupSerializer
    queryset = GamePlaceconfLolGroup.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class GamePlaceconfLolConsoleViewSet(viewsets.ModelViewSet):
    __title__ = "LOL机位系数"
    __group__ = "游戏活动"
    __info__ = {
        "get": "查询LOL机位系数",
        "post": "创建LOL机位系数",
        "patch": "编辑LOL机位系数",
        "delete": "移除LOL机位系数",
    }
    __doc__ = """	list:
    <h4>LOL机位系数列表</h4>
    retrieve:
    <h4>LOL机位系数详情</h4>
    create:
    <h4>创建LOL机位系数</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL机位系数</h4>"""
    http_method_names = ["get", "post", "patch", "delete"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GamePlaceconfLolConsoleSerializer
    queryset = GamePlaceconfLolConsole.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["pid"]

    # search_fields = ['phone','email']
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class GamePlaceconfLolDateViewSet(viewsets.ModelViewSet):
    __title__ = "LOL时间系数"
    __group__ = "游戏活动"
    __info__ = {
        "get": "查询LOL时间系数",
        "post": "创建LOL时间系数",
        "patch": "编辑LOL时间系数",
        "delete": "移除LOL时间系数",
    }
    __doc__ = """	list:
    <h4>LOL时间系数列表</h4>
    retrieve:
    <h4>LOL时间系数详情</h4>
    create:
    <h4>创建LOL时间系数</h4>
    partial_update:
    <h4>编辑LOL时间系数</h4>
    delete:
    <h4>移除LOL时间系数</h4>"""
    http_method_names = ["get", "post", "patch", "delete"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GamePlaceconfLolDateSerializer
    queryset = GamePlaceconfLolDate.objects.all()

    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["pid"]

    # search_fields = ['phone','email']
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class GamePlaceconfLolTasksViewSet(viewsets.ModelViewSet):
    __title__ = "LOL任务系数"
    __group__ = "游戏活动"
    __info__ = {
        "get": "查询LOL任务系数",
        "post": "创建LOL任务系数",
        "patch": "编辑LOL任务系数",
        "delete": "移除LOL任务系数",
    }
    __doc__ = """	list:
    <h4>LOL任务系数列表</h4>
    retrieve:
    <h4>LOL任务系数详情</h4>
    create:
    <h4>创建LOL任务系数</h4>
    partial_update:
    <h4>编辑LOL任务系数</h4>
    delete:
    <h4>移除LOL任务系数</h4>"""
    http_method_names = ["get", "post", "patch", "delete"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GamePlaceconfLolTasksSerializer
    queryset = GamePlaceconfLolTasks.objects.all()

    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["pid", "name"]

    # search_fields = ['phone','email']
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


# ===========================================================


class GameLolHonebaoListViewSet(viewsets.ModelViewSet):
    __title__ = "玩家游戏成就"
    __group__ = "游戏活动"
    __info__ = {"get": "查询玩家游戏成就列表", "put": "编辑玩家游戏成就"}
    __doc__ = """	
    list:
    <h4>查询玩家游戏成就列表</h4>
    retrieve:
    <h4>查询玩家游戏成就详情</h4>
    update:
    <h4>编辑玩家游戏成就</h4>
    """
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GameLolHonebaoListSerializer
    queryset = GameLolHonebaoList.objects.all()

    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    filterset_fields = ["pid", "mid", "status", "answer", "computername"]
    filterset_class = GameLolHonebaoListFilterSet
    search_fields = ["summonerid", "summonername", "cn_champion"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        if instance.status == 1:
            raise serializers.ValidationError("数据已关闭")
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(lasttime=timezone.now(), answer=request.user.id)
        return Response({"rescode": 200, "resmsg": serializer.data})


class GameLolHonebaoListPayedViewSet(viewsets.ModelViewSet):
    __title__ = "兑换LOL红包"
    __group__ = "游戏活动"
    __info__ = {"post": "兑换LOL红包"}
    __doc__ = """
    create:
    <h4>兑换LOL红包</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [
        WeChatJWTAuthentication,
        BarJWTAuthentication,
    ]
    permission_classes = [WeChatPermissions | BarPermissions]
    serializer_class = GameLolEnvelopeSerializer
    queryset = GameLolHonebaoList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        # 检测场所
        if not redis_key_get("loginPlace", request.user.id) == str(
            serializer.data.get("pid")
        ):
            raise serializers.ValidationError("登录场所认证失败")
        # 处理数据
        try:
            instance = self.queryset.get(
                code=serializer.data.get("code"),
                pid=serializer.data.get("pid"),
                status=0,
            )
        except BaseException as err:
            raise serializers.ValidationError("查找数据失败")
        sess = GameLolHonebaoListSerializer(
            instance,
            data={
                "status": 1,
                "answer": request.user.id,
                "lasttime": timezone.now(),
                "code": "",
            },
            partial=True,
        )
        sess.is_valid(raise_exception=True)
        sess.save()

        # 查询会员
        try:
            # vip = AllinpayMemberList.objects.get(id=instance.mid)
            vip = GameLolUseropenidList.objects.get(id=instance.mid)
        except BaseException as err:
            openid = None
        else:
            openid = vip.openid
        # 模板消息
        if openid:
            r = WeAppsOpenidformSend.delay(
                (
                    openid,
                    f"https://we.hs6686.com/#/lol?id={instance.id}",
                    "提现成功通知",
                    [instance.wx_money, timezone.now().strftime("%Y年%m月%d日 %H:%M:%S")],
                )
            )
        return Response({"rescode": 200, "resmsg": sess.data})


# ======================================================================
class GameLolUseropenidListViewSet(viewsets.ModelViewSet):
    __title__ = "LOL玩家账户"
    __group__ = "游戏活动"
    __info__ = {"get": "查询LOL玩家账户"}
    __doc__ = """	
    list:
    <h4>LOL玩家账户列表</h4>
    retrieve:
    <h4>LOL玩家账户详情</h4>"""
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GameLolUseropenidListSerializer
    queryset = GameLolUseropenidList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["userid"]
    # search_fields = ['phone','email']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class LoginGameLolUseropenidListViewSet(viewsets.ModelViewSet):
    __title__ = "LOL玩家登录"
    __group__ = "游戏活动"
    __info__ = {"post": "LOL玩家登录"}
    __doc__ = """
    create:
    <h4>LOL玩家登录</h4>
        该接口登录失败则返回带参数的公众号二维码地址
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = LoginGameLolUseropenidListSerializer
    queryset = GameLolUseropenidList.objects.all()

    def has_code_info(self, mid):
        """返回公众号二维码"""
        try:
            api = requests_Wechat_SDK()
            api.getConf()
            url = "/cgi-bin/qrcode/create"
            headers = api.has_headers()
            params = {"access_token": api.has_access_token()}
            data = {
                "expire_seconds": 172800,
                "action_name": "QR_STR_SCENE",
                "action_info": {"scene": {"scene_str": f"{mid}"}},
            }
            r = api.do_post(
                url=url, headers=headers, params=params, data=json.dumps(data)
            )
            # logger.info(f"[xml] [GET] {r}")
            return r
        except BaseException as err:
            logger.warn(f"[xml] [err] {err}")
            return None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        try:
            r = self.get_queryset().get(**serializer.data)
        except BaseException as err:
            res = self.has_code_info(serializer.data)
            return Response(
                {"rescode": 207, "resmsg": res, "userid": serializer.data["userid"]}
            )
        else:
            return Response(
                {"rescode": 200, "resmsg": GameLolUseropenidListSerializer(r).data}
            )


class PostGameLolDataListViewSet(viewsets.ModelViewSet):
    __title__ = "LOL游戏成就上传"
    __group__ = "游戏活动"
    __info__ = {"get": "查询", "LOL游戏成就上传": "创建", "patch": "编辑", "delete": "移除"}
    __doc__ = """
    create:
    <h4>LOL游戏成就上传</h4>
        sess = {}
        sess["pid"] = pid
        sess["mid"] = mid.id
        sess["computername"] = data.get("jUserInfo_Json", {}).get("ComputerName")  # 机号
        sess["summonerid"] = data.get("summonerId")  # 游戏账号ID
        sess["summonername"] = data.get("summonerName")  # 召唤师名
        sess["area_cname"] = data.get("jUserInfo_Json", {}).get("area_cname")  # 大区信息
        sess["tier"] = data.get("jUserInfo_Json", {}).get("Tier")  # 段位等级
        sess["cn_champion"] = data.get("battle_ratio_json", {}).get("cn_Champion")  # 英雄名称
        sess["cn_gamemode"] = data.get("battle_ratio_json", {}).get("cn_GameMode")  # 游戏模式
        sess["cn_gametype"] = data.get("battle_ratio_json", {}).get("cn_GameType")  # 游戏类型
        sess["win"] = data.get("battle_ratio_json", {}).get("Win")  # 1 胜利；2 失败
        sess["winpoint"] = data.get("battle_ratio_json", {}).get("WinPoint")  # 胜点
        sess["start_time"] = data.get("battle_ratio_json", {}).get("start_time")  # 对局开始时间
        sess["stop_time"] = data.get("battle_ratio_json", {}).get("stop_time")  # 对局结束时间
        sess["lol_money"] = data.get("battle_ratio_json", {}).get("lol_money")  # 奖励金额基数
        sess["firstwin"] = data.get("battle_ratio_json", {}).get(
            "WB_FirstWinBonus_Multiple"
        )  # 首胜奖励倍数
        sess["seat_ratio"] = data.get("battle_ratio_json", {}).get("seat_ratio")  # 座位系数
        sess["tier_ratio"] = data.get("battle_ratio_json", {}).get("tier_ratio")  # 段位系数
        sess["time_ratio"] = data.get("battle_ratio_json", {}).get("time_ratio")  # 时间系数
        sess["area_ratio"] = data.get("battle_ratio_json", {}).get("area_ratio")  # 大区系数
        sess["type_ratio"] = data.get("battle_ratio_json", {}).get("type_ratio")  # 赛制系数
        sess["wx_money"] = data.get("battle_ratio_json", {}).get(
            "wx_money"
        )  # 红包金额 = 奖励金额*系数
        sess["status"] = 0
        sess["currentime"] = timezone.now()
        sess["code"] = has_Random()    
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = PostGameLolDataListSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        logger.debug(f"[Hongbao] {serializer.data}")
        # 创建数据
        data = serializer.data.copy()
        # 检测场所
        pid = has_pid_from_idcode("龙魂编码", data.get("WBCode"))
        if not pid:
            raise serializers.ValidationError("该场所未注册")

        # TASKS.Q8doGameXiaguList(pid, data.get("data"))
        r = TASKS.Q8doGameXiaguList.apply_async((pid, data.get("data")))

        return Response({"rescode": 200, "resmsg": "ok"})


# ==================================================
# ===========新 LOL 对局数据 上传====================
# ==================================================


class LOLResDataUploadSerializerViewSet(viewsets.ModelViewSet):
    __title__ = "LOL对局数据上传"
    __group__ = "游戏活动"
    __info__ = {"post": "LOL对局数据上传"}
    __doc__ = """
    create:
    <h4>LOL对局数据上传</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = LOLResDataUploadSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        # 创建数据
        data = serializer.data.copy()
        # r = TASKS.LOL_Chess_Data_Upload(**data)
        r = TASKS.LOL_Chess_Data_Upload.apply_async(kwargs=data)
        return Response({"rescode": 200, "resmsg": "success"})


class GameLolChessListViewSet(viewsets.ModelViewSet):
    __title__ = "LOL对局数据查询"
    __group__ = "游戏活动"
    __info__ = {"get": "查询LOL对局数据查询", "post": "创建", "patch": "编辑", "delete": "移除"}
    __doc__ = """	
    list:
    <h4>LOL对局数据列表</h4>
    retrieve:
    <h4>LOL对局数据详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GameLolChessListSerializer
    queryset = GameLolChessList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_class = GameLolChessListFilterSet
    # filterset_fields = ["pid", "computer", "puuid"]
    # search_fields = ['phone','email']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class GameLolRewardListViewSet(viewsets.ModelViewSet):
    __title__ = "LOL玩家成就查询"
    __group__ = "游戏活动"
    __info__ = {"get": "LOL玩家成就查询", "post": "创建", "patch": "编辑", "delete": "移除"}
    __doc__ = """	
    list:
    <h4>LOL玩家成就查询列表</h4>
    retrieve:
    <h4>LOL玩家成就查询详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GameLolRewardListSerializer
    queryset = GameLolRewardList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_class = GameLolRewardListFilterSet
    # filterset_fields = ["pid", "computer", "puuid"]
    # search_fields = ['phone','email']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class GameLolPayactListViewSet(viewsets.ModelViewSet):
    __title__ = "LOL奖励兑换"
    __group__ = "游戏活动"
    __info__ = {"get": "LOL奖励兑换查询", "post": "创建LOL奖励兑换"}
    __doc__ = """	list:
    <h4>LOL奖励兑换列表</h4>
    retrieve:
    <h4>LOL奖励兑换详情</h4>
    create:
    <h4>创建LOL奖励兑换</h4>
    """
    http_method_names = ["get", "post", "patch", "delete"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = GameLolPayactListSerializer
    queryset = GameLolPayactList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["pid", "gameid", "openid", "superid", "creatday"]
    # search_fields = ['phone','email']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        t = timezone.now()
        sid = 1 if settings.DEBUG else request.user.id
        sne = "测试员工" if settings.DEBUG else request.user.basename
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(superid=sid, supername=sne, creatime=t, creatday=t.day())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


# 检查视图
filter_views(globals())
